<template>
    <!--面包屑-->
    <div style="margin-bottom: 30px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <router-link to="/Settlements/InputInvoiceShow">进项发票管理</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>进项发票显示</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <table style="width: 80%;">
        <tr>
            <td>
                单位名称:<el-input v-model="form.InvoicingUnit" style="width: 200px" clearable />
            </td>
            <td>
                发票类型:<el-select v-model="form.InvoiceType" style="width: 200px" clearable>
                    <el-option label="普通发票" :value="1" />
                    <el-option label="增值税发票" :value="2" />
                </el-select>
            </td>
            <td>
                开票日期:<el-date-picker v-model="form.InvoicingDate" value-forma="YYYY-MM-DD" style="width: 200px" type="date" clearable />
            </td>
        </tr>
        <tr>
            <td>

            </td>
            <td>

            </td>
            <td>
                <!-- <div v-show="form.buttonArray.includes('getInvoiceList')" class="table-operation"
                    style="margin-top: 8px;"> -->
                <el-button type="primary" @click="getInvoiceList()" :icon="Search">查询</el-button>
                <!-- </div> -->

                <!-- <div v-show="form.buttonArray.includes('reset')" class="table-operation" style="margin-top: 8px;"> -->
                <el-button :icon="RefreshRight" @click="reset()">重置</el-button>
                <!-- </div> -->
            </td>
        </tr>
    </table>
    <!-- <div v-show="form.buttonArray.includes('addInvoice')" class="table-operation" style="margin-top: 8px;"> -->
    <el-button type="primary" @click="addInvoice()">新增</el-button>
    <!-- </div> -->

    <!-- <div v-show="form.buttonArray.includes('batchDel')" class="table-operation" style="margin-top: 8px;"> -->
    <el-button type="primary" @click="batchDel()">批量删除</el-button>
    <!-- </div> -->

    <!-- <div v-show="form.buttonArray.includes('print')" class="table-operation" style="margin-top: 8px;"> -->
    <el-button type="primary" @click="print()">打印</el-button>
    <!-- </div> -->

    <!-- <div v-show="form.buttonArray.includes('exceptExcel')" class="table-operation" style="margin-top: 8px;"> -->
    <el-button type="primary" @click="exceptExcel()">导出</el-button>
    <!-- </div> -->

    <el-table :data="invoiceList" border style="width: 100%;text-align: center;margin-top: 10px"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column prop="invoiceNumber" label="发票号" />
        <el-table-column prop="invoicingUnit" label="开票单位" />
        <el-table-column prop="invoiceType" label="发票类型">
            <template v-slot="scope">
                {{ scope.row.invoiceType == 1 ? '普通发票' : '增值税发票' }}
            </template>
        </el-table-column>
        <el-table-column prop="invoiceValue" label="发票金额" />
        <el-table-column prop="taxRate" label="税率">
            <template v-slot="scope">
                {{ scope.row.taxRate }}%
            </template>
        </el-table-column>
        <el-table-column label="税额">
            <template v-slot="scope">
                {{ (scope.row.invoiceValue * scope.row.taxRate * 0.01).toFixed(2) }}
            </template>
        </el-table-column>
        <el-table-column prop="invoicingDate" label="开票日期">
            <template v-slot="scope">
                <span v-if="scope.row.invoicingDate == null ? '' : scope.row.invoicingDate">{{
                    scope.row.invoicingDate.substring(0, 10) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注">
            <template v-slot="scope">
                {{ scope.row.notes ? scope.row.notes : '-' }}
            </template>
        </el-table-column>
        <el-table-column prop="invoiceCreator" label="制单人" />
        <el-table-column prop="createdDate" label="创建时间">
            <template v-slot="scope">
                <span v-if="scope.row.createdDate == null ? '' : scope.row.createdDate">{{
                    scope.row.createdDate.substring(0, 16).replace("T", " ") }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="242">
            <template v-slot="scope">
                <!-- <div v-show="form.buttonArray.includes('jumpInvoiceUpd')" class="table-operation"
                    style="margin-top: 8px;"> -->
                <el-button @click="jumpInvoiceUpd(scope.row.invoiceId)" type="primary" size="small" link
                    :icon="Edit">编辑</el-button>
                <!-- </div> -->

                <!-- <div v-show="form.buttonArray.includes('delInvoice')" class="table-operation" style="margin-top: 8px;"> -->
                <el-button @click="delInvoice(scope.row)" type="primary" size="small" link
                    :icon="CircleCloseFilled">删除</el-button>
                <!-- </div> -->

                <!-- <div v-show="form.buttonArray.includes('jumpInspect')" class="table-operation" style="margin-top: 8px;"> -->
                <el-button @click="jumpInspect(scope.row.invoiceId)" type="primary" size="small" link
                    :icon="CircleCheckFilled">查看</el-button>
                <!-- </div> -->
            </template>
        </el-table-column>
    </el-table>

    <table style="float: right;">
        <tr>
            <td>
                <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
                    :page-sizes="[3, 5, 8, 10]" :background="true" prev-text="上一页" next-text="下一页"
                    layout="total, slot, prev, pager, next" :total="form.totalCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <span>,每页{{ form.pageSize }}条,共{{ form.pageIndex }}/{{ form.totalPage }}页</span>
                    <el-button class="btn-prev" :disabled="form.pageIndex == 1"
                        @click="handleCurrentChange(1)">首页</el-button>
                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
                    :page-sizes="[3, 5, 8, 10]" :background="true" prev-text="上一页" next-text="下一页"
                    layout="slot, sizes,jumper" :total="form.totalCount" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                    <el-button class="btn-prev" :disabled="form.pageIndex == form.totalPage"
                        @click="handleCurrentChange(form.totalPage)">尾页</el-button>
                </el-pagination>
            </td>
        </tr>
    </table>

    <el-dialog v-model="dialogFormVisible" title="进项发票详情" width="700">
        <table border
            style="border-collapse: collapse; margin-left: 10%;width: 500px;height: 500px;text-align: center;">
            <tr>
                <td>发票号:</td>
                <td>
                    {{ form1.invoiceNumber }}
                </td>
            </tr>
            <tr>
                <td>开票单位:</td>
                <td>
                    {{ form1.invoicingUnit }}
                </td>
            </tr>
            <tr>
                <td>发票类型:</td>
                <td>
                    {{ Number(form1.invoiceType) == 1 ? '普通发票' : '增值税发票' }}
                </td>
            </tr>
            <tr>
                <td>发票金额:</td>
                <td>
                    {{ form1.invoiceValue }}
                </td>
            </tr>
            <tr>
                <td>税率:</td>
                <td>
                    {{ form1.taxRate }}%
                </td>
            </tr>
            <tr>
                <td>税额:</td>
                <td>
                    {{ Number(form1.invoiceValue) * Number(form1.taxRate) * 0.01 }}
                </td>
            </tr>
            <tr>
                <td>开票日期:</td>
                <td>
                    {{ form1.invoicingDate.substring(0, 10) }}
                </td>
            </tr>
            <tr>
                <td>制单人:</td>
                <td>
                    {{ form1.invoiceCreator }}
                </td>
            </tr>
            <tr>
                <td>备注:</td>
                <td>
                    {{ form1.notes }}
                </td>
            </tr>
        </table>
    </el-dialog>

</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import * as XLSX from 'xlsx';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Edit, CircleCheckFilled, CircleCloseFilled, RefreshRight } from '@element-plus/icons-vue'
const router = useRouter()
const route = useRoute()
const form = reactive({
    InvoicingUnit: '',
    CustomerName: '',
    InvoiceType: '',
    InvoicingDate: '',
    InvoiceClassify: 1,
    companyID: '',
    pageIndex: 1,
    pageSize: 3,
    totalCount: 0,
    totalPage: 0,
    buttonArray: ['jumpInvoiceUpd', 'getInvoiceList', 'reset', 'addInvoice', 'batchDel', 'print', 'exceptExcel', 'delInvoice', 'jumpInspect']
})

//根据菜单id查询按钮功能权限
const getRoleMenuFun = () => {
    axios.get('http://47.96.109.219:5202/api/RoleMenuFun/RoleMenuFunId', {
        params: {
            menuId: route.query.id
        }
    }).then(res => {
        console.log(res);
        form.buttonArray = res.data.data
    }).catch(err => {
        console.log(err);

    })
}

//显示进项发票列表
const invoiceList = ref([])
const getInvoiceList = () => {
    axios.get("/jread/api/Invoice/Show", {
        params: {
            InvoicingUnit: form.InvoicingUnit,
            CustomerName: form.CustomerName,
            InvoiceType: form.InvoiceType || 0,
            InvoicingDate: form.InvoicingDate,
            InvoiceClassify: form.InvoiceClassify,
            CompanyID: form.companyID,
            PageIndex: form.pageIndex,
            PageSize: form.pageSize,
        }
    })
        .then((res) => {
            invoiceList.value = res.data.data.list
            form.totalCount = res.data.data.totalCount
            form.totalPage = res.data.data.totalPage
        })
        .catch((err) => {
            console.log(err)
        })
}

//分页
const handleSizeChange = (val: number) => {
    form.pageSize = val
    getInvoiceList()
}
const handleCurrentChange = (val: number) => {
    form.pageIndex = val
    getInvoiceList()
}



//删除
const delInvoice = (row: any) => {
    ElMessageBox.confirm(
        '确认要删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("/swrite/api/Invoice/Delete", row)
                .then((res) => {
                    if (res.data.code == 0) {
                        ElMessage.success("删除成功");
                        getInvoiceList();
                    }
                })
                .catch((err) => {
                    console.log(err)
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作',
            })
        })
}

//定义一个变量，用来存储单条
const selectedData = ref(null);
//存储多条数据
const selectedData1 = ref([]);
//批删/打印选中
const multipleSelection = ref([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val   //批删
    selectedData1.value = val
    if (val.length > 0) {
        selectedData.value = val
    }
    else {
        selectedData.value = null
    }
    // console.log(selectedData.value)
    // console.log(multipleSelection.value)
}

//导出
const exceptExcel = () => {
    ElMessageBox.confirm("是否确认导出当前所选中的进项发票数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
    .then((response) => {
        //  this.selectdata 是复选框的 数据列表
        if (multipleSelection.value.length <= 0) {
            ElMessage.warning('请选择数据！');
            return;
        }
        let tableData = [
            ['序号','发票号', '开票单位', '发票类型', '发票金额', '税率', "税额", "开票日期", "制单人", "创建时间"]//导出表头
        ] // 表格表头
        multipleSelection.value.forEach((item, index) => {
            let rowData = []
            //导出内容的字段
            rowData = [
                index + 1,
                item.invoiceNumber,
                item.invoicingUnit,
                item.invoiceType == 1 ? "普通发票" : "增值税发票",
                item.invoiceValue,
                item.taxRate+"%",
                item.invoiceValue * item.taxRate / 100,
                item.invoicingDate.substring(0,10),
                item.invoiceCreator,
                item.createdDate.substring(0, 16).replace("T"," "),
            ]
            tableData.push(rowData)
        })
        let workSheet = XLSX.utils.aoa_to_sheet(tableData);
        let bookNew = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(bookNew, workSheet, '作品名称') // 工作簿名称
        let name = '进项发票管理' + timeFormat() + '.xlsx'
        XLSX.writeFile(bookNew, name) // 保存的文件名
    })
}
const timeFormat=()=> {
        let time = new Date();
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let date = time.getDate();
        let hours = time.getHours();
        let minutes = time.getMinutes();
        let seconds = time.getSeconds();
        return year + '-' + addZero(month) + '-' + addZero(date) + ' ' + addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds);
}
const addZero=(num:any)=> {
    return num < 10 ? '0' + num : num
}
      


// 创建打印内容
const createPrintContent = (data: any) => {
    //打印单条
    // console.log(data[0])
    // if (!data) return '';
    // return `
    //     <div style="font-family: Arial, sans-serif;">
    //         <h1>进项发票详情</h1>
    //         <p>发票号: ${data[0].invoiceNumber}</p>
    //         <p>开票单位: ${data[0].invoicingUnit}</p>
    //         <p>发票类型: ${data[0].invoiceType == 1 ? '普通发票' : '增值税发票'}</p>
    //         <p>发票金额: ${data[0].invoiceValue}</p>
    //         <p>税率: ${data[0].taxRate}%</p>
    //         <p>税额: ${data[0].invoiceValue * data[0].taxRate * 0.01}</p>
    //         <p>开票日期: ${data[0].invoicingDate.substring(0, 10)}</p>
    //         <p>制单人: ${data[0].invoiceCreator}</p>
    //     </div>
    // `;

    //打印多条
    if (!data || data.length === 0) return '';
    let printContent = '<div style="font-family: Arial, sans-serif;">';
    printContent += '<h1>进项发票详情</h1>';
    printContent += '<table border="1" style="width: 100%; border-collapse: collapse;">';
    printContent += '<tr><th>发票号</th><th>开票单位</th><th>发票类型</th><th>发票金额</th><th>税率</th><th>税额</th><th>开票日期</th><th>制单人</th><th>备注</th></tr>';

    data.forEach((item: any) => {
        printContent += `<tr>
            <td>${item.invoiceNumber}</td>
            <td>${item.invoicingUnit}</td>
            <td>${item.invoiceType == 1 ? '普通发票' : '增值税发票'}</td>
            <td>${item.invoiceValue}</td>
            <td>${item.taxRate}%</td>
            <td>${(item.invoiceValue * item.taxRate * 0.01).toFixed(2)}</td>
            <td>${item.invoicingDate.substring(0, 10)}</td>
            <td>${item.invoiceCreator}</td>
            <td>${item.notes ? item.notes : '-'}</td>
        </tr>`;
    });

    printContent += '</table>';
    printContent += '</div>';
    return printContent;
}

// 打印选中的数据
const print = () => {
    if (!selectedData1.value || selectedData1.value.length === 0) {
        ElMessage({
            message: '请选择要打印的发票',
            type: 'warning',
        });
        return;
    }
    const printContent = createPrintContent(selectedData1.value);
    const printWindow = window.open('', '_blank');
    printWindow.document.write(printContent);
    printWindow.document.close();
    printWindow.print();
    printWindow.close();
}

//批删
const batchDel = () => {
    ElMessageBox.confirm(
        '确认要删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            var ids: any = [];
            multipleSelection.value.forEach((item: any) => {
                ids.push(item.invoiceId)
                // console.log(ids)
            })
            axios.post("/swrite/api/Invoice/BatchDel?InvoiceId=" + ids)
                .then((res) => {
                    if (res.data.code == 0) {
                        ElMessage.success("删除成功");
                        getInvoiceList();
                    }
                })
                .catch((err) => {
                    console.log(err)
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作',
            })
        })
}

//跳转修改页面
const jumpInvoiceUpd = (invoiceId: any) => {
    router.push({
        name: '/InputInvoiceUpdate',
        query: {
            invoiceId: invoiceId
        }
    })
}

const dialogFormVisible = ref(false);
//打开查看弹窗
const jumpInspect = (invoiceId: any) => {
    dialogFormVisible.value = true;
    getInvoiceModel(invoiceId);
}
const form1 = reactive({
    createdBy: "张三",  // 创建人   
    createdDate: new Date(),    // 创建日期
    updatedBy: "张三",  // 更新人
    updatedDate: new Date(),     // 更新日期
    // deletedBy: "",  // 删除人
    // deletedDate: "",    // 删除日期
    isDeleted: false,        // 是否删除
    invoiceId: 0, // 发票ID
    companyID: "", // 公司ID
    user_Id: 0, // 用户ID
    invoiceNumber: "", // 发票号码
    invoicingUnit: "", // 开票单位
    customerName: "", // 客户名称
    invoiceType: '', // 发票类型
    invoiceValue: '', // 发票金额
    taxRate: '', // 税率 
    invoicingDate: "",  // 开票日期
    notes: "",  // 备注
    invoiceCreator: "李四", // 开票人
    invoiceClassify: 1, // 发票分类
})
//返填
const getInvoiceModel = (invoiceId: any) => {
    axios.get("/jread/api/Invoice/Backfill?InvoiceId=" + invoiceId)
        .then(res => {
            form1.createdBy = res.data.data.createdBy;
            form1.createdDate = res.data.data.createdDate;
            form1.updatedBy = res.data.data.updatedBy;
            form1.updatedDate = res.data.data.updatedDate;
            // form1.deletedBy= res.data.data.deletedBy;
            // form1.deletedDate= res.data.data.deletedDate;
            form1.isDeleted = res.data.data.isDeleted;
            form1.invoiceId = res.data.data.invoiceId;
            form1.companyID = res.data.data.companyID;
            form1.user_Id = res.data.data.user_Id;
            form1.invoiceNumber = res.data.data.invoiceNumber;
            form1.invoicingUnit = res.data.data.invoicingUnit;
            form1.customerName = res.data.data.customerName;
            form1.invoiceType = res.data.data.invoiceType;
            form1.invoiceValue = res.data.data.invoiceValue;
            form1.taxRate = res.data.data.taxRate;
            form1.invoicingDate = res.data.data.invoicingDate;
            form1.notes = res.data.data.notes;
            form1.invoiceClassify = res.data.data.invoiceClassify;
            form1.invoiceCreator = res.data.data.invoiceCreator;
        })
        .catch(err => {
            console.log(err);
        })
}
//重置查询条件
const reset = () => {
    form.CustomerName = "";
    form.InvoiceType = "";
    form.InvoicingDate = "";
    form.InvoicingUnit = "";
    getInvoiceList()
}

//跳转新增进项发票页面
const addInvoice = () => {
    router.push("InputInvoiceAdd")
}

onMounted(() => {
    getInvoiceList();
    getRoleMenuFun();
})
</script>